var cameraValue, renderer, camera, scene, gui, stats, ambientLight, directionalLight, control, group, panel, isMobile, isIOS, cameraZ, canvasjq, canvas, context, scaleLimit, stippleTimer;
const CameraConfig = {
    pc: {
        factor: 50,
        scale: 2700,
    },
    mobile: {
        factor: 10,
        scale: 400,
    }
};
window.onload = enterPage;

function enterPage() {
    initData();
    initThree();
    initDomComponent();
    window.onresize = onWindowResize;
}

function initData() {
    scaleLimit = 1.2;
    let info = Utils.checkDeviceType(navigator.userAgent);
    isMobile = info.isMobile;
    cameraValue = isMobile ? CameraConfig.mobile : CameraConfig.pc;
}

function initDomComponent() {
    panel = $("#view");
    if (isMobile) {
        panel[0].addEventListener("touchstart", function(e) {
            modelControler(e.touches[0].clientX, e.touches[0].clientY);
        });
    } else {
        panel.mousemove(function(e) {
            modelControler(e.clientX, e.clientY);
        });
    }
}

function modelControler(x, y) {
    let s = y - window.innerHeight;
    let ca = camera.aspect < 1 ? 1 : camera.aspect;
    // console.log(camera.aspect);
    if (ca < scaleLimit) {
        cameraZ = (1 - ca + s / cameraValue.scale) * cameraValue.factor;
    } else {
        cameraZ = (1 - scaleLimit + s / cameraValue.scale) * cameraValue.factor;
    }
}

function initThree() {
    initRender();
    initScene();
    initCamera();
    initLight();
    initModel();
    rendererUpdate();
}

function initRender() {
    canvasjq = $("#canvas");
    canvas = canvasjq[0];
    renderer = new THREE.WebGLRenderer({
        antialias: true,
        canvas: canvas,
    });
    renderer.setClearColor(0xffffff); //为渲染器设置颜色
    renderer.setSize(window.innerWidth, window.innerHeight);
    // document.body.appendChild(renderer.domElement);
    canvasjq.css({
        float: "left",
        top: "0",
        left: "0",
        position: "absolute",
        "z-index": "-10",
    });
}

function initCamera() {
    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.position.set(0, 0, 0);
    camera.lookAt(scene.position);
    if (camera.aspect < scaleLimit) {
        cameraZ = (1 - camera.aspect) * cameraValue.factor;
    } else {
        cameraZ = (1 - scaleLimit) * cameraValue.factor;
    }
}

function initScene() {
    scene = new THREE.Scene();
}

function initLight() {
    ambientLight = new THREE.AmbientLight("#ffffff");
    scene.add(ambientLight);
}

function initModel() {
    group = new THREE.Group();
    var geometry = new THREE.BoxGeometry(20, 20, 20)
    var material = new THREE.MeshLambertMaterial({
        color: 0xd0d0d0,
        wireframe: false,
        transparent: true,
        opacity: 0,
    });
    // material.color = color;
    var box = new THREE.Mesh(geometry, material);
    group.add(box);
    box.position.set(0, -15, 0);
    box.visible = false;
    //创建MTL加载器
    var mtlLoader = new THREE.MTLLoader();
    //设置文件路径
    mtlLoader.setPath('./data/');
    //加载mtl文件
    mtlLoader.load('box_miku.mtl', function(material) {
        //创建OBJ加载器
        var objLoader = new THREE.OBJLoader();
        objLoader.transparent = true;
        //设置当前加载的纹理
        material.transparent = true;
        // material.side = THREE.FrontSide;
        objLoader.setMaterials(material);
        objLoader.setPath('./data/');

        function setopacity(o, v, b) {
            for (let i = 0; i < o.children[0].material.length; i++) {
                let m = o.children[0].material[i];
                if (b) {
                    m.transparent = true;
                }
                m.opacity = v;
            }
        }
        objLoader.load('box_miku.obj', function(object) {
            // console.log(object);
            object.visible = false;
            object.scale.set(3, 3, 3);
            object.transparent = true;
            object.name = "miku"
            group.add(object);
            object.position.set(0, -6, 0);
            var t = new TWEEN.Tween(0).to(1, 1000).onUpdate(function(v) {
                setopacity(object, v);
                box.material.opacity = v;
            }).onComplete(function() {
                setopacity(object, 1);
                box.material.opacity = 1;
                t.stop();
                stipple();
            }).onStart(function() {
                setopacity(object, 0, true);
                object.visible = true;
                box.material.opacity = 0;
                box.visible = true;
            }).start();
        }, function(event) {
            // console.log(event);
            //若长度可以计算
            if (event.lengthComputable) {
                // object.
                console.log("now process : " + event.loaded / event.total * 100 + "%");
            }
        })
    });
    scene.add(group);
    group.position.set(0, -10, -50);
}

function stipple() {}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    if (camera.aspect < scaleLimit) {
        cameraZ = (1 - camera.aspect) * cameraValue.factor;
    } else {
        cameraZ = (1 - scaleLimit) * cameraValue.factor;
    }
}

function rendererUpdate() {
    renderer.render(scene, camera);
    group.rotation.y += 0.02;
    requestAnimationFrame(rendererUpdate);
    if (Math.abs(camera.position.z - cameraZ) > 0.01) {
        camera.position.z = Utils.lerp(camera.position.z, cameraZ, 0.2);
    } else {
        camera.position.z = cameraZ;
    }
    TWEEN.update();
}